﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using CarbonExchange.Logger;
using System.Web.Security;

namespace CarbonExchange.WebControls
{
    public class HttpModule : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        void context_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            if (app != null)
            {
                HttpCookie cookie = app.Context.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
                {
                    try
                    {
                        System.Web.Security.FormsAuthenticationTicket ticket = System.Web.Security.FormsAuthentication.Decrypt(cookie.Value);
                        if (ticket != null)
                        {
                            Guid key = Guid.Empty;
                            try
                            {
                                key = new Guid(ticket.Name);
                            }
                            catch (FormatException)
                            {
                            }

                            if (key != Guid.Empty)
                            {
                                app.Context.User = new CarbonExchange.Bll.UserPrinciple(key);
                            }
                        }
                    }
                    catch (System.Security.Cryptography.CryptographicException)
                    {
                    }
                }
            }
        }


        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            if (app != null)
            {
                string path = app.Context.Request.AppRelativeCurrentExecutionFilePath;

                if (path.EndsWith(".aspx"))
                {
                    string postCacheKey = string.Concat(path);
                    Bll.CarbonExchangeContext postContext = app.Context.Cache[postCacheKey] as Bll.CarbonExchangeContext;
                    if (postContext == null)
                    {
                        ILogger log = StructureMap.ObjectFactory.GetInstance<ILogger>();
                        log.Info(string.Format("Getting Context for '{0}'", path));
                        string siteRoot = app.Context.Request.ServerVariables["Server_Name"];
                        if (app.Context.Request.ApplicationPath != "/")
                            siteRoot += app.Context.Request.ApplicationPath;
                        postContext = new Bll.CarbonExchangeContext(siteRoot, path);

                        DateTime endTime = DateTime.Now.AddHours(1);
                        app.Context.Cache.Insert(postCacheKey, postContext, null, endTime, TimeSpan.Zero, System.Web.Caching.CacheItemPriority.BelowNormal, null);
                    }

                    app.Context.Items.Add("CarbonExchangeContext", postContext);
                }
            }
        }
    }
}
